<?php
include 'includes/header.php';
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

// Handle status update
if (isset($_POST['update_status'])) {
    $query = "UPDATE inquiries SET status = ?, response = ? WHERE id = ?";
    $stmt = $db->prepare($query);
    $stmt->execute([$_POST['status'], $_POST['response'], $_POST['inquiry_id']]);
}

// Handle delete
if (isset($_GET['delete'])) {
    $delete_query = "DELETE FROM inquiries WHERE id = ?";
    $delete_stmt = $db->prepare($delete_query);
    if ($delete_stmt->execute([$_GET['delete']])) {
        set_message('Inquiry deleted successfully', 'success');
    } else {
        set_message('Error deleting inquiry', 'danger');
    }
    redirect('inquiries.php');
}

// Get all inquiries with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

$inquiries_query = "SELECT i.*, c.title as car_title, u.first_name, u.last_name, u.email, u.phone, u.username 
                    FROM inquiries i 
                    LEFT JOIN cars c ON i.car_id = c.id 
                    LEFT JOIN users u ON i.user_id = u.id 
                    ORDER BY i.created_at DESC 
                    LIMIT :offset, :per_page";
$stmt = $db->prepare($inquiries_query);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':per_page', $per_page, PDO::PARAM_INT);
$stmt->execute();
$inquiries = $stmt->fetchAll();

$total_inquiries = $db->query("SELECT COUNT(*) FROM inquiries")->fetchColumn();
$total_pages = ceil($total_inquiries / $per_page);
?>

<div class="container-fluid py-4">
    <h2 class="mb-4">Manage Inquiries</h2>
    
    <div class="card shadow">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Car</th>
                            <th>User</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Message</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($inquiries as $inquiry): ?>
                        <tr>
                            <td><?php echo date('Y-m-d', strtotime($inquiry['created_at'])); ?></td>
                            <td>
                                <a href="../car-details.php?id=<?php echo $inquiry['car_id']; ?>">
                                    <?php echo htmlspecialchars($inquiry['car_title']); ?>
                                </a>
                            </td>
                            <td><?php echo htmlspecialchars($inquiry['username']); ?></td>
                            <td><?php echo htmlspecialchars($inquiry['name']); ?></td>
                            <td>
                                <a href="mailto:<?php echo $inquiry['email']; ?>">
                                    <?php echo htmlspecialchars($inquiry['email']); ?>
                                </a>
                            </td>
                            <td>
                                <a href="tel:<?php echo $inquiry['phone']; ?>">
                                    <?php echo htmlspecialchars($inquiry['phone']); ?>
                                </a>
                            </td>
                            <td><?php echo htmlspecialchars(substr($inquiry['message'], 0, 50)) . '...'; ?></td>
                            <td>
                                <span class="badge bg-<?php echo $inquiry['status'] == 'Pending' ? 'warning' : 'success'; ?>">
                                    <?php echo $inquiry['status']; ?>
                                </span>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#viewInquiryModal<?php echo $inquiry['id']; ?>">
                                    View
                                </button>
                                <button class="btn btn-sm btn-success" onclick="updateStatus(<?php echo $inquiry['id']; ?>, 'Responded')">
                                    Mark Responded
                                </button>
                                <a href="inquiries.php?delete=<?php echo $inquiry['id']; ?>" 
                                   class="btn btn-sm btn-danger"
                                   onclick="return confirm('Are you sure you want to delete this inquiry?')">
                                    Delete
                                </a>
                            </td>
                        </tr>
                        
                        <!-- View Inquiry Modal -->
                        <div class="modal fade" id="viewInquiryModal<?php echo $inquiry['id']; ?>" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title">Inquiry Details</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <div class="mb-3">
                                            <strong>Date:</strong> <?php echo date('Y-m-d H:i', strtotime($inquiry['created_at'])); ?>
                                        </div>
                                        <div class="mb-3">
                                            <strong>Car:</strong> <?php echo htmlspecialchars($inquiry['car_title']); ?>
                                        </div>
                                        <div class="mb-3">
                                            <strong>User:</strong> <?php echo htmlspecialchars($inquiry['username']); ?>
                                        </div>
                                        <div class="mb-3">
                                            <strong>Name:</strong> <?php echo htmlspecialchars($inquiry['name']); ?>
                                        </div>
                                        <div class="mb-3">
                                            <strong>Email:</strong> 
                                            <a href="mailto:<?php echo $inquiry['email']; ?>">
                                                <?php echo htmlspecialchars($inquiry['email']); ?>
                                            </a>
                                        </div>
                                        <div class="mb-3">
                                            <strong>Phone:</strong>
                                            <a href="tel:<?php echo $inquiry['phone']; ?>">
                                                <?php echo htmlspecialchars($inquiry['phone']); ?>
                                            </a>
                                        </div>
                                        <div class="mb-3">
                                            <strong>Message:</strong><br>
                                            <?php echo nl2br(htmlspecialchars($inquiry['message'])); ?>
                                        </div>
                                        <div class="mb-3">
                                            <strong>Status:</strong> <?php echo $inquiry['status']; ?>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                        <button type="button" class="btn btn-success" onclick="updateStatus(<?php echo $inquiry['id']; ?>, 'Responded')">
                                            Mark as Responded
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <?php if ($total_pages > 1): ?>
            <nav class="mt-4">
                <ul class="pagination justify-content-center">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function updateStatus(inquiryId, status) {
    fetch('inquiries.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `update_status=1&inquiry_id=${inquiryId}&status=${status}`
    })
    .then(response => {
        if (response.ok) {
            location.reload();
        } else {
            alert('Error updating status');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating status');
    });
}
</script>

<?php include 'includes/footer.php'; ?> 